package com.emser.unc.server.restlet;


import org.restlet.Application;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.ChallengeScheme;
import org.restlet.resource.Directory;
import org.restlet.routing.Router;
import org.restlet.security.ChallengeAuthenticator;
import org.restlet.security.MapVerifier;


public class ApplicationRestlet extends Application {
	private ChallengeAuthenticator authenticatior;
	private ChallengeAuthenticator createAuthenticator() {
        Context context = getContext();
        boolean optional = true;
        ChallengeScheme challengeScheme = ChallengeScheme.HTTP_BASIC;
        String realm = "Example site";
        MapVerifier verifier = new MapVerifier(); 
        verifier.getLocalSecrets().put("user", "password".toCharArray());
        ChallengeAuthenticator auth = new ChallengeAuthenticator(context, optional, challengeScheme, realm, verifier) {
            @Override
            protected boolean authenticate(Request request, Response response) {
                if (request.getChallengeResponse() == null) {
                    return false;
                } else {
                    return super.authenticate(request, response);
                }
            }
        };
        return auth;
    }
	@Override
	public Restlet createInboundRoot() {
		this.authenticatior = createAuthenticator();
        Router router = new Router(getContext());
        router.attachDefault(new Directory(getContext(), "war:///"));
        router.attach("/login", SellerServerResource.class); 
        router.attach("/customer",CustomerServerResource.class);
        router.attach("/salereport",SaleReportServerResource.class);
        router.attach("/location",LocationServerResource.class);
        router.attach("/product",ProductServerResource.class);
        router.attach("/nosalereport",NoSaleReportServerResource.class);
        router.attach("/version",VersionServerResource.class);
        authenticatior.setNext(router);
        return authenticatior;  
	}
	
	public boolean authenticate(Request request, Response response) {
        if (!request.getClientInfo().isAuthenticated()) {
            authenticatior.challenge(response, false);
            return false;
        }
        return true;
    }
}
